package com.supercube.sport.yoga.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.supercube.common.dao.DictDao;
import com.supercube.common.domain.DictDO;
import com.supercube.common.utils.ShiroUtils;
import com.supercube.common.utils.StringUtils;
import com.supercube.sport.yoga.bo.CourseFormsBo;
import com.supercube.sport.yoga.bo.GoodsStockBo;
import com.supercube.sport.yoga.bo.PerformanceDetailsBo;
import com.supercube.sport.yoga.bo.ReportFormsBo;
import com.supercube.sport.yoga.dao.VenueInfoDTOMapper;
import com.supercube.sport.yoga.reportForms.CourseFormsDTO;
import com.supercube.sport.yoga.reportForms.DailyForms;
import com.supercube.sport.yoga.service.ReportFormsService;
import com.supercube.sport.yoga.utils.ExcelUtils;
import com.supercube.sport.yoga.utils.ResultInfo;
import com.supercube.sport.yoga.vo.GoodsStockVo;
import com.supercube.sport.yoga.vo.VenueInfoVO;
import com.supercube.system.dao.UserDao;
import com.supercube.system.domain.UserDO;
import com.supercube.system.vo.UserBO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * Description：
 * Created By guowen
 */
@RestController
@RequestMapping("/reportForms")
@Api(tags = "报表")
@Slf4j
public class ReportFormsController {
    @Autowired
    private ReportFormsService reportFormsService;
    @Autowired
    UserDao userMapper;
    @Autowired
    DictDao dictMapper;
    @Autowired
    VenueInfoDTOMapper venueInfoDTOMapper;

    @ApiOperation(value = "查询日报表列表", notes = "查询日报表列表")
    @PostMapping("/getDailyReportList")
    public ResultInfo getDailyReportList (@RequestBody ReportFormsBo bo) {
        PageHelper.startPage(bo.getPageNum(), bo.getPageSize());
        List<DailyForms> list = reportFormsService.getDailyReportList(bo);
        PageInfo<DailyForms> pageInfo = new PageInfo<>(list);
        return ResultInfo.success(pageInfo);
    }
    @ApiOperation(value = "导出日报表列表", notes = "导出日报表列表")
    @PostMapping("/exportDailyReportList")
    public void exportDailyReportList (HttpServletResponse response, @RequestBody ReportFormsBo bo) {
        try {
            VenueInfoVO venue = venueInfoDTOMapper.selectByPrimaryKey(bo.getVenueId());
            List<DailyForms> list = reportFormsService.getDailyReportList(bo);
            ExcelUtils.exportExcel(response,"日报表","静波瑜伽（"+venue.getName()+"）店"+getMonth(bo.getCountDate())+"月销售日报表",list,DailyForms.class);
        } catch (Exception e) {
            log.error("导出日报表列表", e);
        }
    }

    /*
           1:[12,34,54,23,213,11]
           2:[12,34,54,23,213,11]
     */
    @ApiOperation(value = "查询业绩明细列表", notes = "查询业绩明细列表")
    @PostMapping("/getPerformanceDetailsReportList")
    public ResultInfo getPerformanceDetailsReportList (@RequestBody ReportFormsBo bo) {
        List<Map<String, BigDecimal[]>> result = getMaps(bo);
        List<BigDecimal[]> list = new ArrayList<>();
        for(int i=0;i<result.size();i++){
            Map<String, BigDecimal[]> m = result.get(i);
            for(Map.Entry<String, BigDecimal[]> vo : m.entrySet()){
                list.add(vo.getValue());
            }
        }
        return ResultInfo.success(list);
    }

    @ApiOperation(value = "导出业绩明细列表", notes = "导出业绩明细列表")
    @PostMapping("/exportPerformanceDetailsReportList")
    public void exportPerformanceDetailsReportList (HttpServletResponse response, @RequestBody ReportFormsBo bo) {
        try {
            List<Map<String, BigDecimal[]>> result = getMaps(bo);
            UserBO userBO = new UserBO();
            //查询销售与教练，empType=2:教练；empType=null:为销售
            userBO.setEmpType(null);
            userBO.setUserId(ShiroUtils.getUserId());
            userBO.setVenueId(bo.getVenueId());
            List<UserDO> userList = userMapper.queryCoachAndSaleList(userBO);
            List<String> headList = new ArrayList<>();
            headList.add("日期");
            userList.forEach(u->{
                headList.add(u.getName());
            });
            VenueInfoVO venue = venueInfoDTOMapper.selectByPrimaryKey(bo.getVenueId());
            ExcelUtils.exportExcel2(response,"业绩明细","静波瑜伽（"+venue.getName()+"）店"+getMonth(bo.getCountDate())+"月业绩明细明细表",result,headList);
        } catch (Exception e) {
            log.error("导出业绩明细列表", e);
        }
    }

    private List<Map<String, BigDecimal[]>> getMaps(ReportFormsBo bo) {
        UserBO userBO = new UserBO();
        //查询销售与教练，empType=2:教练；empType=null:为销售
        userBO.setEmpType(null);
        userBO.setUserId(ShiroUtils.getUserId());
        userBO.setVenueId(bo.getVenueId());
        List<UserDO> userList = userMapper.queryCoachAndSaleList(userBO);
        List<Map<String, BigDecimal[]>> result = new ArrayList();
        if(CollectionUtil.isNotEmpty(userList)){
            int endDay = getMonthDays(bo.getCountDate());
            BigDecimal[] allAmounts = new BigDecimal[userList.size()];
            //初始化合计行
            for (int j = 0; j < userList.size(); j++) {
                allAmounts[j] = new BigDecimal("0");
            }
            for (int i = 1; i <= endDay; i++) {
                Map<String, BigDecimal[]> map = new HashMap<>();
                BigDecimal[] amounts = new BigDecimal[userList.size()];
                String day = "";
                if (i < 10) {
                    day = "0" + i;
                } else {
                    day = "" + i;
                }
                List<PerformanceDetailsBo> list = reportFormsService.getPerformanceDetailsReportList(bo.getCountDate() + "-" + day,bo.getVenueId());
                for (int j = 0; j < userList.size(); j++) {
                    UserDO user = userList.get(j);
                    for (PerformanceDetailsBo d : list) {
                        if (Objects.equals(d.getUserId(), user.getUserId())) {
                            amounts[j] = d.getAmount();
                            allAmounts[j] = allAmounts[j].add(amounts[j]);
                            break;
                        }
                    }
                }
                map.put(i + "", amounts);
                result.add(map);
            }
            Map<String, BigDecimal[]> all = new HashMap<>();
            all.put("合计", allAmounts);
            result.add(all);
        }
        return result;
    }

    @ApiOperation(value = "查询收款明细列表", notes = "查询收款明细列表")
    @PostMapping("/getCollectionDetailsReportList")
    public ResultInfo getCollectionDetailsReportList (@RequestBody ReportFormsBo bo) {
        List<Map<String, BigDecimal[]>> result = getCollectionMaps(bo);
        List<BigDecimal[]> list = new ArrayList<>();
        for(int i=0;i<result.size();i++){
            Map<String, BigDecimal[]> m = result.get(i);
            for(Map.Entry<String, BigDecimal[]> vo : m.entrySet()){
                list.add(vo.getValue());
            }
        }
        return ResultInfo.success(list);
    }
    @ApiOperation(value = "导出收款明细列表", notes = "导出收款明细列表")
    @PostMapping("/exportCollectionDetailsReportList")
    public void exportCollectionDetailsReportList (HttpServletResponse response, @RequestBody ReportFormsBo bo) {
        try {
            List<Map<String, BigDecimal[]>> result = getCollectionMaps(bo);
            Map<String, Object> dmap  = new HashMap<>();
            dmap.put("type","payment_method");
            List<DictDO> dictList = dictMapper.list(dmap);
            List<String> headList = new ArrayList<>();
            headList.add("日期");
            dictList.forEach(d->{
                headList.add(d.getName());
            });
            headList.add("总收款");
            VenueInfoVO venue = venueInfoDTOMapper.selectByPrimaryKey(bo.getVenueId());
            ExcelUtils.exportExcel2(response,"收款明细","静波瑜伽（"+venue.getName()+"）店"+getMonth(bo.getCountDate())+"月收款明细表",result,headList);
        } catch (Exception e) {
            log.error("导出收款明细列表", e);
        }
    }
    private List<Map<String, BigDecimal[]>> getCollectionMaps(ReportFormsBo bo) {
        // 查询支付方式
        Map<String, Object> dmap  = new HashMap<>();
        dmap.put("type","payment_method");
        List<DictDO> dictList = dictMapper.list(dmap);
        int endDay = getMonthDays(bo.getCountDate());
        List<Map<String, BigDecimal[]>> result = new ArrayList();
        int length = dictList.size();
        BigDecimal[] allAmounts = new BigDecimal[length+1];
        //初始化合计行
        for (int j = 0; j < length+1; j++) {
            allAmounts[j] = new BigDecimal("0");
        }
        BigDecimal allSum = new BigDecimal("0");
        for (int i = 1; i <= endDay; i++) {
            Map<String, BigDecimal[]> map = new HashMap<>();
            BigDecimal[] amounts = new BigDecimal[length+1];
            String day = "";
            if (i < 10) {
                day = "0" + i;
            } else {
                day = "" + i;
            }
            List<PerformanceDetailsBo> list = reportFormsService.getCollectionDetailsReportList(bo.getCountDate() + "-" + day,bo.getVenueId());
            BigDecimal sum = new BigDecimal("0");
            for (int j = 0; j < length; j++) {
                DictDO dict = dictList.get(j);
                for (PerformanceDetailsBo d : list) {
                    if (Objects.equals(d.getName(), dict.getName())) {
                        amounts[j] = d.getAmount();
                        sum = sum.add(amounts[j]);
                        allAmounts[j] = allAmounts[j].add(amounts[j]);
                        break;
                    }
                }
            }
            amounts[length] = sum;
            allSum = allSum.add(sum);
            map.put(i + "", amounts);
            result.add(map);
        }
        Map<String, BigDecimal[]> all = new HashMap<>();
        allAmounts[length] = allSum;
        all.put("合计", allAmounts);
        result.add(all);
        return result;
    }


    @ApiOperation(value = "查询库存表列表", notes = "查询库存表列表-分页")
    @PostMapping("/getGoodsStockReportList")
    public ResultInfo getGoodsStockReportList (@RequestBody GoodsStockBo bo) {
        PageHelper.startPage(bo.getPageNum(), bo.getPageSize());
        List<GoodsStockVo> list = reportFormsService.getGoodsStockReportList(bo);
        PageInfo<GoodsStockVo> pageInfo = new PageInfo<>(list);
        return ResultInfo.success(pageInfo);
    }

    @ApiOperation(value = "查询库存表列表", notes = "查询库存表列表-不分页")
    @PostMapping("/queryGoodsList")
    public ResultInfo queryGoodsList (@RequestBody GoodsStockBo bo) {
        bo.setPageNum(null);
        bo.setPageSize(null);
        List<GoodsStockVo> list = reportFormsService.getGoodsStockReportList(bo);
        return ResultInfo.success(list);
    }

    @ApiOperation(value = "导出库存表列表", notes = "导出库存表列表")
    @PostMapping("/exportGoodsStockReportList")
    public void exportGoodsStockReportList (HttpServletResponse response, @RequestBody GoodsStockBo bo) {
        try {
            List<GoodsStockVo> list = reportFormsService.getGoodsStockReportList(bo);
            VenueInfoVO venue = venueInfoDTOMapper.selectByPrimaryKey(bo.getVenueId());
            ExcelUtils.exportExcel(response,"库存表","静波瑜伽（（"+venue.getName()+"））店库存统计表",list,GoodsStockVo.class);
        } catch (Exception e) {
            log.error("导出库存表列表", e);
        }
    }

    @ApiOperation(value = "查询课程报表列表", notes = "查询课程报表列表")
    @PostMapping("/getCourseReportList")
    public ResultInfo getCourseReportList (@RequestBody CourseFormsBo bo) {
        List<CourseFormsDTO> list = reportFormsService.getCourseReportList(bo);
        return ResultInfo.success(list);
    }
    @ApiOperation(value = "导出课程表列表", notes = "导出日课程列表")
    @PostMapping("/exportCourseReportList")
    public void exportCourseReportList (HttpServletResponse response, @RequestBody CourseFormsBo bo) {
        try {
            String venueName = "全部";
            if(StringUtils.isNotBlank(bo.getVenueId())){
                VenueInfoVO venue = venueInfoDTOMapper.selectByPrimaryKey(bo.getVenueId());
                venueName = venue.getName();
            }
            List<CourseFormsDTO> list = reportFormsService.getCourseReportList(bo);
            ExcelUtils.exportExcel3(response,"课程表","静波瑜伽（"+venueName+"）店"+bo.getStartDate()+"/"+bo.getEndDate()+"课程报表",list,CourseFormsDTO.class);
        } catch (Exception e) {
            log.error("导出课程表列表", e);
        }
    }




    private int getMonthDays(String countDate) {
        int year = Integer.parseInt(countDate.substring(0, countDate.indexOf('-')));
        int mth = Integer.parseInt(countDate.substring(countDate.indexOf('-')+1));
        Calendar calendar = Calendar.getInstance();
        calendar.clear();//在使用set方法之前，必须先clear一下，否则很多信息会继承自系统当前时间
        calendar.set(Calendar.YEAR,year);
        calendar.set(Calendar.MONTH,mth-1);//Calendar对象默认一月为0          
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);//获得本月的天数
    }

    private int getMonth(String countDate){
        return Integer.parseInt(countDate.substring(countDate.indexOf('-')+1));
    }

}
